<template>
  <div class="h-full w-full">
    <SplitPanel :style="{ 'flex-direction': 'row !important' }" class="user-page-box">
      <template #left-content>
        <div class="flex justify-between flex-col h-full">
          <a-input-search
            v-model:value="searchValue"
            style="margin-bottom: 8px"
            placeholder="请输入"
          />
          <Tree
            v-model:expandedKeys="state.expandedKeys"
            auto-expand-parent
            :tree-data="state.deptTree"
            @select="onTreeSelect"
          >
          </Tree>
        </div>
      </template>
      <template #right-content>
        <DynamicTable
          header-title="人员管理"
          show-index
          title-tooltip="请不要随意删除用户，避免到影响其他用户的使用。"
          :data-request="loadTableData"
          :columns="columns"
        >
          <template #toolbar>
            <a-button type="primary" @click="openUserModal({})"> <PlusOutlined /> 新增 </a-button>
          </template>
        </DynamicTable>
      </template>
    </SplitPanel>
  </div>
</template>

<script setup lang="tsx">
  import { ref, reactive, computed, onMounted, h, watch ,defineComponent,unref} from 'vue';
  import { message } from 'ant-design-vue';
  import {
    PlusOutlined,
    EditOutlined,
    DeleteOutlined,
    FileSyncOutlined,
  } from '@ant-design/icons-vue';
  import type { FormInstance } from 'ant-design-vue';
  import { Tree, Modal, Alert } from 'ant-design-vue';
  import { userSchemas, updatePswSchemas,blankData } from './formSchemas';
  import { baseColumns, type TableListItem, type TableColumnItem } from './columns';
  import type { LoadDataParams } from '@/components/core/dynamic-table';
  import type { TreeDataItem } from '@/core/permission/utils';
  import { SplitPanel } from '@/components/basic/split-panel';
  import { useTable } from '@/components/core/dynamic-table';
  import {
    deleteUsers,
    getUserListPage,
    getUserInfo,
    createUser,
    updateUser,
    beforeAdd,
    updateUserPassword,
  } from '@/api/system/user';
  import { getOrgList } from '@/api/organization/orgs/orgs';
  import {formatFormSortTree,formatExpandFormSortTree} from '@/views/organization/orgs/columns';
  import { getDeptsList, getDepartmentEntityList } from '@/api/organization/depts/depts';
  import { useFormModal } from '@/hooks/useModal/index';
  import { formatDept2Tree, findChildById, flatTree } from '@/core/permission/utils';
  import { useModal } from '@/hooks/useModal/useModal';
  import UserDetail from '@/views/organization/users/userDetail.vue';
  import { cloneDeep } from 'lodash-es';

  defineOptions({
    name: 'SystemUser',
  });
  defineComponent({
    UserDetail
  })

  interface State {
    expandedKeys:string[];
    parentId: number[];
    departmentIds: number[];
    originData: any;
    deptTree: TreeDataItem[];
  }

  const [DynamicTable, dynamicTableInstance] = useTable({ formProps: { autoSubmitOnEnter: true } });
  const [ModalRender, modalRef] = useModal();
  const userDetailRef = ref<FormInstance>();

  const searchValue = ref('');

  const searchTree = (tree, keyword, includeChildren = false) => {
    const newTree: any = [];
    for (let i = 0; i < tree.length; i++) {
      const node = tree[i];
      if (node.title.includes(keyword)) {
        if (!state.parentId.includes(node.key) && node.children && node.children.length) {
          state.parentId.push(node.key);
        }
        newTree.push({
          ...node,
          children: includeChildren ? searchTree(node.children || [], '', true) : [],
        });
      } else if (node.children) {
        const result = searchTree(node.children, keyword, true);
        if (result.length > 0) {
          state.parentId.push(node.key);
          newTree.push({ ...node, children: result });
        }
      }
    }
    return newTree;
  };

  watch(
    () => searchValue.value,
    (newVal) => {
      state.deptTree = searchTree(state.originData, newVal, true);
    },
  );

  const deptListLoading = ref(false);

  const state = reactive<State>({
    expandedKeys:[],
    parentId: [],
    departmentIds: [],
    deptTree: [],
    originData: [],
  });

  const rowSelection = ref({
    selectedRowKeys: [] as number[],
    onChange: (selectedRowKeys: number[], selectedRows: TableListItem[]) => {
      console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
      rowSelection.value.selectedRowKeys = selectedRowKeys;
    },
  });

  // 是否勾选了表格行
  const isCheckRows = computed(() => rowSelection.value.selectedRowKeys.length);

  /**
     * @description 打开用户弹窗
     */
  const editDrawerBindValue = reactive({
    orgData: [],
    postList:[],
    pubStation:[],
    userInfo: {},
  });
  const openUserModal = async (record: Partial<TableListItem> = {}) => {
    editDrawerBindValue.userInfo=record.userId?{...record}:{...blankData};
    ModalRender.show({
      title: `${record.userId ? '编辑' : '新增'}用户`,
      width: '50%',
      destroyOnClose: true,
      bodyStyle:{ height: '60vh', overflowY: 'auto' },
      content: () => {
        return <UserDetail ref={userDetailRef} defaultData={unref(editDrawerBindValue)}></UserDetail>;
      },
      // 确定方法执行
      onOk: async (values) => {
        const [userInfo,userRef] = await userDetailRef.value?.handleSubmit();
        let res = await userRef.value.validate()
        console.log(userInfo,"userinfo11111111111111111111111")
        if (res) {
          const createUserData=cloneDeep(userInfo);
          const isAdd=record.userId ? false : true;
          const userList=await beforeAdd(createUserData);
          if(userList.result.length==1&&isAdd==true){
            message.error("登录名已经存在，请重新设置");
            return false;
          }
          else{
            //辅助岗
            if(userInfo.orgId!==undefined&&userInfo.orgId.length>0&&Array.isArray(userInfo.orgId)){
              const postStr=createUserData.orgId.map(item=>item.toString());
              const posts=postStr.join(',');
              createUserData.orgId=posts;
            }

            createUserData.id=record.userId ? record.userId:"";
            const result=await (record.userId ? updateUser : createUser)(createUserData);
            if(result.error===200){
              const msg=record.userId ? "修改成功":"新增成功";
              message.success(msg);
              dynamicTableInstance?.reload();
            }
          }
          
        };
      },
  });
};
  
  /**
   * 打开更新用户密码弹窗
   */
  const openUpdatePasswordModal = async (record: TableListItem) => {
    await updateUserPassword({
      id: record.userId,
    });
  };

  /**
   * 获取部门列表
   */
  const fetchDeptList = async () => {
    deptListLoading.value = true;
    const res = await getDepartmentEntityList().finally(() => (deptListLoading.value = false));
    console.log(res);
    if (res && res.result) {
      const dept = flatTree(res.result);
      state.deptTree = formatDept2Tree(dept, '0');
      state.originData = state.deptTree.map((item) => item);
      state.parentId = [...state.parentId, ...state.deptTree.map((n: any) => Number(n.id))];
    }
    // const res = await getOrgList().finally(() => (deptListLoading.value = false));
    // if (res && res.result) {
    //   const orgs = flatTree(res.result);
    //   state.deptTree = formatFormSortTree(orgs, '0');
    //   state.originData = state.deptTree.map((item) => item);
    //   state.parentId = [...state.parentId, ...state.deptTree.map((n: any) => Number(n.id))];
    // }
  };
 /**
   * 
   * @param selectedKeys 展开
   */
   const onExpand=async(node:any) => {
    // alert(selectedKeys)
    console.log(node)
    const data = await getDeptsList({
      pageSize: 10000,
      pageNum:1,
      orgId: node.dataModel=='org'?node.value:'',
      parentId: node.value,
      name: '',
    });
    // console.log(data,111111111111);
    
    if(data.rows.length>0){
      state.expandedKeys = [...state.expandedKeys,node.value];
      node.dataRef.children = formatExpandFormSortTree(data.rows,node.value)
      console.log(formatExpandFormSortTree(data.rows,node.value));
      
      state.deptTree = [...state.deptTree]
    }
    
  };
  /**
   * @description 表格删除行
   */
  const delRowConfirm = async (userId: number) => {
    await deleteUsers({ userId: userId }).finally(dynamicTableInstance?.reload);
  };

  /**
   * 点击部门
   */
  const onTreeSelect = (selectedKeys: number[]) => {
    state.departmentIds = selectedKeys;
    dynamicTableInstance?.reload?.();
  };

  const loadTableData = async (params: LoadDataParams) => {
    const data = await getUserListPage({
      ...params,
      pageSize: params.limit,
      orgId: state.departmentIds.length ? state.departmentIds[0] : '',
    });
    rowSelection.value.selectedRowKeys = [];
    return {
      list: data?.rows || [],
      pagination: {
        total: data.total,
        size: params.limit,
        page: params.pageNum,
      },
    } as API.TableListResult;
  };

  const columns: TableColumnItem[] = [
    ...baseColumns,
    {
      title: '操作',
      width: 350,
      dataIndex: 'ACTION',
      align: 'center',
      actions: ({ record }) => [
        {
          label: '编辑',
          icon: h(EditOutlined),
          onClick: () => openUserModal(record),
        },
        {
          label: '重置密码',
          icon: h(FileSyncOutlined),
          popConfirm: {
            title: '你确定要重置密码吗？',
            onConfirm: () => openUpdatePasswordModal(record),
          },
        },
        {
          label: '删除',
          danger: true,
          icon: h(DeleteOutlined),
          popConfirm: {
            title: '你确定要删除吗？',
            onConfirm: () => delRowConfirm(record.userId),
          },
        },
      ],
    },
  ];

  onMounted(() => {
    fetchDeptList();
  });
</script>

<style lang="less" scoped>
  @import '@/styles/navTheme.less';
  @classBacks: user-page-box;
  .customSetStyle(@classBacks, background-color, 'content-back-user');

  :deep(.ant-tree) {
    flex: 1;
  }
</style>
